package com.sc.nft.admin.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.meta.user.client.api.MetaUserClient;
import com.sc.nft.admin.request.*;
import com.sc.nft.annotation.SysMemberLogin;
import com.sc.nft.config.sand.SandConfig;
import com.sc.nft.config.sand.SandPayUtil;
import com.sc.nft.dao.*;
import com.sc.nft.dto.AdminUserWorkRoomExportDTO;
import com.sc.nft.dto.EcologyHatchRewardsConfDao;
import com.sc.nft.dto.UserEcologyHatchRecordsDao;
import com.sc.nft.dto.UserEcologyHatchRewardsRecordsDao;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.MarketValueAccountRegistrationDTO;
import com.sc.nft.entity.vo.UserLoginVO;
import com.sc.nft.enums.CycleCollectionEnum;
import com.sc.nft.enums.DaoLevelTypeEnum;
import com.sc.nft.enums.MarketTypeEnum;
import com.sc.nft.enums.PayStatusEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.pool.SysMemberPool;
import com.sc.nft.service.*;
import com.sc.nft.sup.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/dealWith")
@Api(tags = "批量处理")
public class DealWithController {
    private final UserInfoService userInfoService;
    private final UserCollectionService userCollectionService;
    private final DigitalCollectionDao digitalCollectionDao;
    private final SecondCollectionConfigDao secondCollectionConfigDao;
    private final ReportAmountService reportAmountService;
    private final ReportTransferService reportTransferService;
    private final ReportUserService reportUserService;
    private final UserInfoDao userInfoDao;
    private final ReportBalanceService reportBalanceService;
    private final IdcardInfoDao idcardInfoDao;
    private final PayOrderDao payOrderDao;
    private final MallPayOrderRecordDao mallPayOrderRecordDao;
    private final SecondCollectionService secondCollectionService;
    private final UserWorkRoomService userWorkRoomService;
    private final RedisTemplate redisTemplate;
    private final UserEcologyHatchIncomeService userEcologyHatchIncomeService;
    private final UserEcologyHatchRecordsDao userEcologyHatchRecordsDao;
    private final EcologyHatchRewardsConfDao ecologyHatchRewardsConfDao;
    private final UserEcologyPointsService userEcologyPointsService;
    private final UserEcologyNotSettleListDao userEcologyNotSettleListDao;
    private final EcologyHatchCollecionShareProfitConfDao ecologyHatchCollecionShareProfitConfDao;
    private final EquityPropsService equityPropsService;
    private final UserEquityPropsService userEquityPropsService;
    private final UserEcologyHatchRewardsRecordsDao userEcologyHatchRewardsRecordsDao;
    private final MetaUserClient userClient;

    @PostMapping(value = "/batchRegistration", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "批量注册用户", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin
    public Result batchRegistration(@Valid @RequestBody BatchRegistrationUserTelRequest request) {
        List<String> list = request.getList();
        for (String userTel : list) {
            userInfoService.registeUser(request.getInviteCode(), 1, userTel, "123456");
        }
        return Result.success();
    }

    @PostMapping(value = "/batchBind", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "批量绑定用户", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin
    public Result batchBind(@Valid @RequestBody List<BatchBindRequest> request) {
        for (BatchBindRequest b : request) {
            userClient.inviteWithUserTel(b.getUserTel(), b.getInviteCode());
        }
        return Result.success();
    }


    @PostMapping(value = "/forBind", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "循环绑定关系网体", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin
    public Result forBind(@Valid @RequestBody List<BatchBindRequest> request) {
        int i = 1;
        for (BatchBindRequest b : request) {
            if (ObjectUtil.isNotNull(userInfoDao.getOneByUserTel(b.getUserTel()))) {
                continue;
            }
            UserInfo parentInfo = userInfoDao.getOneByUserTel(b.getParentUserTel());
            if (ObjectUtil.isNull(parentInfo) || StrUtil.isBlank(parentInfo.getInviteCode())) {
                continue;
            }
            userInfoService.registeUser(parentInfo.getInviteCode(), 1, b.getUserTel(), "123456");

            log.info("第{}条", i++);

        }
        return Result.success();
    }


    @PostMapping(value = "/marketValueAccountRegistration", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "批量注册市值账号", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin
    public Result marketValueAccountRegistration(@Valid @RequestBody MarketValueAccountRegistrationDTO marketValueAccountRegistrationDTO) {
        for (Integer count = marketValueAccountRegistrationDTO.getCount(); count > 0; count--) {
            UserInfo byUserTel = userInfoService.getByUserTel(marketValueAccountRegistrationDTO.getUserTel());
            if (BeanUtil.isNotEmpty(byUserTel)) {
                count++;
                marketValueAccountRegistrationDTO.setUserTel(String.valueOf(Long.parseLong(marketValueAccountRegistrationDTO.getUserTel()) + 1));
            } else {
                UserLoginVO userLoginVO = userInfoService.marketValueAccountRegistration("111111", 1, marketValueAccountRegistrationDTO.getUserTel(), "123456");
                marketValueAccountRegistrationDTO.setUserTel(String.valueOf(Long.parseLong(marketValueAccountRegistrationDTO.getUserTel()) + 1));
                FilterIncomeList filterIncomeList = new FilterIncomeList();
                filterIncomeList.setUserId(userLoginVO.getUserId());
                filterIncomeList.setDaoId(0L);
                filterIncomeList.setProportion(BigDecimal.ZERO);
                filterIncomeList.insert();
            }
        }
        return Result.success();
    }

    @PostMapping(value = "/resetAntiHoard", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "重置品牌孵化防囤", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin
    public Result resetAntiHoard() {

        List<SecondCollectionConfig> list = secondCollectionConfigDao.getListByStatusAndMarketType(MarketTypeEnum.BRAND_INCUBATION);
        for (SecondCollectionConfig secondCollectionConfig : list) {
            DigitalCollection digitalCollection = digitalCollectionDao.getById(secondCollectionConfig.getCollectionId());
            userCollectionService.initAnti(digitalCollection);
        }
        return Result.success();
    }

//    @PostMapping(value = "/initReport", produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiOperation(value = "初始化报表数据", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    @ResponseBody
//    @SysMemberLogin
//    public Result initReport(@Valid @RequestBody InitReportRequest request) throws ParseException {
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Date day = sdf.parse("2022-06-13");
//        while (true) {
//            day = addDay(day, 1);
//            String format = sdf.format(day);
//            System.out.println(format);
//            reportAmountService.insertReportAmountByDay(format);
//            reportTransferService.insertReportTransferByDay(format);
//            reportUserService.insertReportUserByDay(format);
//            if (format.equals(request.getEndTime())) {
//                break;
//            }
//        }
//
//        ReportUser reportUser = new ReportUser();
//        reportUser.setSumPartnerCount(userInfoDao.getPartnerCount());
//        reportUser.setSumCityLordCount(userInfoDao.getCountByLevel(DaoLevelTypeEnum.CITY_LORD));
//        reportUser.setSumResidentCount(userInfoDao.getCountByLevel(DaoLevelTypeEnum.RESIDENT));
//        reportUser.setSumRtouristsCount(userInfoDao.getCountByLevel(DaoLevelTypeEnum.TOURISTS));
//        reportUser.setSumUserCount(userInfoDao.getCount());
//        reportUser.insert();
//        reportBalanceService.insertReportBalance();
//        return Result.success();
//    }

    @PostMapping(value = "/resetAntiReport", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "充值平台账户和财务数据", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin
    public Result resetAntiReport(@Valid @RequestBody InitReportRequest request) throws ParseException {
        // 与相东确认方法已废弃
//        reportBalanceService.insertReportBalance();
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Date day = sdf.parse("2022-06-13");
//        while (true) {
//            day = addDay(day, 1);
//            String format = sdf.format(day);
//            System.out.println(format);
//            reportAmountService.insertReportAmountByDay(format);
//            if (format.equals(request.getEndTime())) {
//                break;
//            }
//        }
        return Result.success();
    }

    @PostMapping(value = "/delUserByUserTel", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "逻辑删除用户", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @SysMemberLogin
    @Transactional(rollbackFor = Exception.class)
    public Result delUserByUserTel(@Valid @RequestBody DelUserByUserTelRequest request) throws ParseException {
        UserInfo user = userInfoDao.getOneByUserTel(request.getUserTel());
        if (ObjectUtil.isNull(user)) {
            return Result.fail("用户不存在");
        }

        String userTel = user.getUserTel();
        char[] charArray = userTel.toCharArray();
        charArray[0] = '2';
        String newTel = new String(charArray);
        UserInfo newUser = userInfoDao.getOneByUserTel(newTel);
        if (ObjectUtil.isNotNull(newUser)) {
            return Result.fail("新手机号已存在,请手动修改: {}" + newTel);
        }


//        user.setUserTel(newTel);
//        user.setIsFreeze(Boolean.TRUE);
//        user.setPwd("a2a52d6f5abe9e050c692b134551733e");
//        user.setNickName(DesensitizedUtil.mobilePhone(newTel));
//        user.setIsSm(Boolean.FALSE);
//        user.updateById();
        userInfoDao.logicDelete(user.getId(), newTel);


        //清除实名信息
        idcardInfoDao.deleteByUserId(user.getId());
        return Result.success();
    }

    @ApiOperation(value = "杉德退款", notes = "杉德退款", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/sandRefundls", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result sandRefundls(@Valid @RequestBody IdRequest request) {
        SysMember member = SysMemberPool.getMember();
        if (!member.getId().equals(18L) && !member.getId().equals(26L) && !member.getId().equals(66L)) {
            throw new GlobalRunTimeException("无权限");
        }
        PayOrder payOrder = payOrderDao.getById(request.getId());
        MallPayOrderRecord mallPayOrderRecord = new MallPayOrderRecord();
        mallPayOrderRecord.setTradeNo(UUID.fastUUID().toString(true));
        mallPayOrderRecord.setRefundAmount(payOrder.getPayAmount());
        mallPayOrderRecord.setNotifyUrl(SandConfig.MALL_REFUND_NOTIFY_URL);
        JSONObject jsonObject = SandPayUtil.refundRequest(mallPayOrderRecord, payOrder.getTradeNo(), "退款");
        payOrder.setStatus(PayStatusEnum.INIT);
        payOrder.setRefundAmount(payOrder.getPayAmount());
        payOrder.updateById();
        log.info("退款流水号:{}", mallPayOrderRecord.getTradeNo());
        log.info(jsonObject.toJSONString());
        return Result.success();
    }

    @ApiOperation(value = "商城杉德退款", notes = "商城杉德退款", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/mall/sandRefundls", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result mallSandRefundls(@Valid @RequestBody IdRequest request) {
        SysMember member = SysMemberPool.getMember();
        if (!member.getId().equals(18L) && !member.getId().equals(26L) && !member.getId().equals(66L)) {
            throw new GlobalRunTimeException("无权限");
        }
        MallPayOrderRecord payOrder = mallPayOrderRecordDao.getById(request.getId());
        MallPayOrderRecord mallPayOrderRecord = new MallPayOrderRecord();
        mallPayOrderRecord.setTradeNo(UUID.fastUUID().toString(true));
        mallPayOrderRecord.setRefundAmount(payOrder.getPayAmount());
        mallPayOrderRecord.setNotifyUrl(SandConfig.MALL_REFUND_NOTIFY_URL);
        JSONObject jsonObject = SandPayUtil.refundRequest(mallPayOrderRecord, payOrder.getTradeNo(), "退款");
        payOrder.setStatus(PayStatusEnum.INIT);
        payOrder.setRefundAmount(payOrder.getPayAmount());
        payOrder.updateById();
        log.info("退款流水号:{}", mallPayOrderRecord.getTradeNo());
        log.info(jsonObject.toJSONString());
        return Result.success();
    }


//    @ApiOperation(value = "生态直推", notes = "生态直推", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    @PostMapping(value = "/getToBeSettledDirectThrustIncomeList", produces = MediaType.APPLICATION_JSON_VALUE)
//    @Ignore
//    public Result getToBeSettledDirectThrustIncomeList() {
//        EcologyHatchIncomeConf incomeConf = ecologyHatchIncomeConfDao.getOneByType(EcologyIncomeTypeEnum.RECOMMENDED_INCOME);
//        //生态节点的藏品id集合
//        List<Long> nodeCollectionIds = ecologyCollectionNodeConfDao.getCollectionList();
//        nodeCollectionIds.add(SpecialIdEnum.RESIDENT_ID.getCollectionId());
//        nodeCollectionIds.add(SpecialIdEnum.CITY_LORD_ID.getCollectionId());
//        //待结算直推收益
//        List<UserEcologyHatchRecords> settleDirectThrustIncomeList = userEcologyHatchRecordsDao.getToBeSettledDirectThrustIncomeList();
//        log.info("需要计算直推记录数:{}",settleDirectThrustIncomeList.size());
//        for (UserEcologyHatchRecords userEcologyHatchRecords : settleDirectThrustIncomeList) {
//            userEcologyHatchIncomeService.settleDirectThrustIncomeList(userEcologyHatchRecords,incomeConf,nodeCollectionIds);
//        }
//        return Result.success();
//    }

    @ApiOperation(value = "插入更新藏品列表", notes = "插入更新藏品列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/insertCycleCollection", produces = MediaType.APPLICATION_JSON_VALUE)
    @Ignore
    public Result insertCycleCollection() {
        secondCollectionService.insertCycleCollection(CycleCollectionEnum.ZHI_TAN);
        secondCollectionService.insertCycleCollection(CycleCollectionEnum.DING_LIAN);
        return Result.success();
    }

    private Date addDay(Date date, Integer day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }


    /**
     * 社区网点数据Excel导出
     *
     * @throws IOException
     */
    @ApiOperation(value = "社区网点数据插入临时表", notes = "社区网点数据插入临时表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/insertUserWorkRoomExport", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result insertUserWorkRoomExport() throws IOException {
        userWorkRoomService.userWorkRoomExport();

        return Result.success();
    }

    /**
     * 社区网点数据Excel导出
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    @ApiOperation(value = "社区网点数据导出", notes = "社区网点数据导出", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public void download(HttpServletResponse response) throws IOException {
        // ，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<AdminUserWorkRoomExportDTO> list = userWorkRoomService.getDataList();
        log.info("导出数据:{}", list);
        EasyExcel.write(response.getOutputStream(), AdminUserWorkRoomExportDTO.class).sheet("模板").doWrite(list);
    }

    /**
     * 用户实名(用户人脸识别失败)
     *
     * @throws IOException
     */
    @ApiOperation(value = "用户实名(用户人脸识别失败)", notes = "用户实名(用户人脸识别失败)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/userRealName", produces = MediaType.APPLICATION_JSON_VALUE)
    @Transactional(rollbackFor = Exception.class)
    public Result insertUserWorkRoomExport(@Valid @RequestBody IdRequest request) throws IOException {
        Assert.isTrue(idcardInfoDao.userRealName(request.getId()), () -> new GlobalRunTimeException("实名记录:修改失败"));
        Assert.isTrue(userInfoDao.userRealName(request.getId()), () -> new GlobalRunTimeException("用户实名表示:修改失败"));
        return Result.success();
    }

    @ApiOperation(value = "删除redis的Key", notes = "删除redis的Key", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/delRedisKey", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result delRedisKey(@Valid @RequestBody DelRedisKeyRequest request) throws IOException {
        redisTemplate.delete(request.getRedisKey().getKey());
        return Result.success();
    }

//    @ApiOperation(value = "补发奖励", notes = "补发奖励", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    @PostMapping(value = "/settlePeriodicReward", produces = MediaType.APPLICATION_JSON_VALUE)
//    public Result adminSettlePeriodicReward() throws IOException {
//
//        List<UserEcologyHatchRecords> settleList = userEcologyHatchRecordsDao.settlePeriodicReward();
////        List<UserEcologyHatchRecords> settleList = userEcologyHatchRecordsDao.getSettleList();
//        int count = 0;
//        for (UserEcologyHatchRecords oldRecords : settleList) {
//            log.info("熔炼周期奖励,当前处理第{}条,总共{}条",count++,settleList.size());
//            //进行中的订单 周期+1天
////            Assert.isTrue(userEcologyHatchRecordsDao.addAlreadyDayByStatusById(oldRecords.getId()),()->new GlobalRunTimeException("更新天数失败"));
//            //获取加了之后的记录
//            UserEcologyHatchRecords userEcologyHatchRecords = userEcologyHatchRecordsDao.getById(oldRecords.getId());
//            settle(userEcologyHatchRecords);
//        }
//
//        return Result.success();
//    }


//    private void settle(UserEcologyHatchRecords userEcologyHatchRecords){
//        //获取熔炼奖励
//        List<EcologyHatchRewardsConf> rewardsConfList = ecologyHatchRewardsConfDao.getListByEcologyHatchId(userEcologyHatchRecords.getEcologyHatchId());
//        for (EcologyHatchRewardsConf ecologyHatchRewardsConf : rewardsConfList) {
//            //判断奖励周期是否为0 如果值是0 则默认为1 因为0不能做为除数
//            int rewardsCycle = ecologyHatchRewardsConf.getRewardsCycle() == 0 ? 1 : ecologyHatchRewardsConf.getRewardsCycle();
//            //判断当前日志是否能被整除
//            log.info("用户记录id:{},熔炼奖励周期{},用户熔炼的天数{}条,取模结果:{}",userEcologyHatchRecords.getId(),rewardsCycle,userEcologyHatchRecords.getAlreadyDay(),userEcologyHatchRecords.getAlreadyDay() % rewardsCycle == 0);
//            log.info("用户记录id:{},熔炼奖励周期{},用户熔炼的天数{}条,取模结果:{}",userEcologyHatchRecords.getId(),rewardsCycle,userEcologyHatchRecords.getAlreadyDay(),userEcologyHatchRecords.getAlreadyDay() % rewardsCycle == 0);
//            log.info("用户记录id:{},熔炼奖励周期{},用户熔炼的天数{}条,取模结果:{}",userEcologyHatchRecords.getId(),rewardsCycle,userEcologyHatchRecords.getAlreadyDay(),userEcologyHatchRecords.getAlreadyDay() % rewardsCycle == 0);
//            if(userEcologyHatchRecords.getAlreadyDay() % rewardsCycle == 0){
//                Long linkId = 0L;
//                //奖励数量
//                BigDecimal amount = ecologyHatchRewardsConf.getLinkCount().multiply(Convert.toBigDecimal(userEcologyHatchRecords.getHatchCount()));
//
//                UserEcologyExpenditureTypeEnum expenditureType = null;
//                EcologyRewardsType rewardsType = null;
//                //生态燃料
//                if(ecologyHatchRewardsConf.getRewardsType() == EcologyRewardsType.ECOLOGY_POINTS){
//                    log.info("用户记录id:{},奖励燃料,跳出",userEcologyHatchRecords.getId());
//                    continue;
//                }else if(ecologyHatchRewardsConf.getRewardsType() == EcologyRewardsType.EQUITY_PROPS){//权益道具
//                    log.info("用户记录id:{},奖励权益道具",userEcologyHatchRecords.getId());
//
//                    expenditureType = UserEcologyExpenditureTypeEnum.EQUITY_PROPS;
//                    rewardsType = EcologyRewardsType.EQUITY_PROPS;
//
//                    EquityProps equityProps = equityPropsService.getById(ecologyHatchRewardsConf.getLinkId());
//                    linkId=equityProps.getId();
//
//                    //查询是否
//                    UserEcologyNotSettleList notSettleList = userEcologyNotSettleListDao.getLastOneByUserIdAndEquityPropsId(userEcologyHatchRecords.getUserId(), ecologyHatchRewardsConf.getLinkId());
//                    if(ObjectUtil.isNull(notSettleList)){
//
//                        log.info("用户记录id:{},不需要过滤",userEcologyHatchRecords.getId());
//
//
//                        //幂等性校验
//                        if(userEcologyHatchRewardsRecordsDao.getIsExistByUserIdAndRecordsId(userEcologyHatchRecords.getUserId(),userEcologyHatchRecords.getId())){
//                            log.info("用户记录id:{},幂等性校验未通过",userEcologyHatchRecords.getId());
//                            continue;
//                        }
//                        //添加权益道具
//                        userEquityPropsService.addEquityPropsByUser(equityProps,userEcologyHatchRecords.getUserId(), UserEquityPropsGetTypeEnum.ECOLOGY_SMELTING_REWARDS,amount.intValue(),StrUtil.format("熔炼:{}",userEcologyHatchRecords.getCollectionName()),userEcologyHatchRecords.getId(),BigDecimal.ZERO);
//                        log.info("用户记录id:{},发放奖励",userEcologyHatchRecords.getId(),equityProps.getFirstTitle());
//
//                    }else{
//                        expenditureType = UserEcologyExpenditureTypeEnum.EQUITY_PROPS;
//                        rewardsType = EcologyRewardsType.EQUITY_PROPS;
//
//                        //需要偿还的数量大于等于当前奖励数量 则直接扣除
//                        if(notSettleList.getFrozenCount() >=  notSettleList.getAlreadyCount() + amount.intValue()){
//                            Assert.isTrue(userEcologyNotSettleListDao.addAlreadyCountById(notSettleList.getId(),amount.intValue()),()->new GlobalRunTimeException("更新次数失败"));
//
//                            UserEcologyNotSettleList newNowSettleRecords = userEcologyNotSettleListDao.getById(notSettleList.getId());
//                            if(newNowSettleRecords.getAlreadyCount().intValue() >= newNowSettleRecords.getFrozenCount().intValue()){
//                                Assert.isTrue(userEcologyNotSettleListDao.deleteById(notSettleList.getId()),()->new GlobalRunTimeException("更新次数失败"));
//                            }
//                            continue;
//                        }else{
//                            //需要偿还的数量小于当前奖励数量 则扣除剩余的数量
//                            int addCount = notSettleList.getAlreadyCount() + amount.intValue() - notSettleList.getFrozenCount();
//                            int remainingCount = notSettleList.getFrozenCount() - notSettleList.getAlreadyCount().intValue();
//
//                            Assert.isTrue(userEcologyNotSettleListDao.addAlreadyCountById(notSettleList.getId(),remainingCount),()->new GlobalRunTimeException("更新次数失败"));
//
//                            UserEcologyNotSettleList newNowSettleRecords = userEcologyNotSettleListDao.getById(notSettleList.getId());
//                            if(newNowSettleRecords.getAlreadyCount().intValue() >= newNowSettleRecords.getFrozenCount().intValue()){
//                                Assert.isTrue(userEcologyNotSettleListDao.deleteById(notSettleList.getId()),()->new GlobalRunTimeException("更新次数失败"));
//                            }
//                            if(addCount> 0){
//                                //添加权益道具
//                                userEquityPropsService.addEquityPropsByUser(equityProps,userEcologyHatchRecords.getUserId(), UserEquityPropsGetTypeEnum.ECOLOGY_SMELTING_REWARDS,addCount,StrUtil.format("熔炼:{}",userEcologyHatchRecords.getCollectionName()),userEcologyHatchRecords.getId(),BigDecimal.ZERO);
//                                amount = Convert.toBigDecimal(addCount);
//                            }
//                        }
//                    }
//                }
//
//                //收入记录表
//                UserEcologyExpenditureRecord userEcologyExpenditureRecord = new UserEcologyExpenditureRecord();
//                userEcologyExpenditureRecord.setUserId(userEcologyHatchRecords.getUserId());
//                userEcologyExpenditureRecord.setType(expenditureType);
//                userEcologyExpenditureRecord.setTypeName(expenditureType.getDescription());
//                userEcologyExpenditureRecord.setRemark(StrUtil.format("熔炼:{}",userEcologyHatchRecords.getCollectionName()));
//                userEcologyExpenditureRecord.setLinkId(linkId);
//                userEcologyExpenditureRecord.setLinkName(ecologyHatchRewardsConf.getLinkName());
//                userEcologyExpenditureRecord.setLinkCount(amount);
//                userEcologyExpenditureRecord.setDateTime(Convert.toInt(DateUtil.format(DateTime.now(), "yyyyMMdd")));
//                userEcologyExpenditureRecord.setLinkImage(ecologyHatchRewardsConf.getLinkImage());
//                userEcologyExpenditureRecord.insert();
//
//                //用户奖励记录表
//                UserEcologyHatchRewardsRecords userEcologyHatchRewardsRecords = new UserEcologyHatchRewardsRecords();
//                userEcologyHatchRewardsRecords.setUserId(userEcologyHatchRecords.getUserId());
//                userEcologyHatchRewardsRecords.setUserEcologyHatchRecordsId(userEcologyHatchRecords.getId());
//                userEcologyHatchRewardsRecords.setEcologyHatchId(userEcologyHatchRecords.getEcologyHatchId());
//                userEcologyHatchRewardsRecords.setRewardsType(rewardsType);
//                userEcologyHatchRewardsRecords.setRewardsTypeName(rewardsType.getDescription());
//                userEcologyHatchRewardsRecords.setIncomeType(EcologyIncomeTypeEnum.CYCLE_INCOME);
//                userEcologyHatchRewardsRecords.setIncomeTypeName(EcologyIncomeTypeEnum.CYCLE_INCOME.getDescription());
//                userEcologyHatchRewardsRecords.setLinkId(linkId);
//                userEcologyHatchRewardsRecords.setLinkName(ecologyHatchRewardsConf.getLinkName());
//                userEcologyHatchRewardsRecords.setLinkCount(amount);
//                userEcologyHatchRewardsRecords.setLinkImge(ecologyHatchRewardsConf.getLinkImage());
//                userEcologyHatchRewardsRecords.insert();
//            }
//
//        }
//    }
}
